package com.alibaba.moco.springboot;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 类CookiesInterceptor.java的实现描述：TODO 将用户配置作为session存储
 * 
 * @author wb-lj240895 2016年12月14日 下午2:03:22
 */
public class SessionInterceptor implements HandlerInterceptor {

    private static final String KEY_CALLBACK_URL = "callback_url";
    private static final String KEY_USERNAME     = "username";
    private static final String URL_CONFIG       = "/pages/config.html";

    private static final Logger logger           = LoggerFactory.getLogger(SessionInterceptor.class);

    /**
     * 只处理请求 中的cookies
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        HttpSession session = request.getSession();
        if (session != null) {

            Object callbackUrl = session.getAttribute(KEY_CALLBACK_URL);
            Object userName = session.getAttribute(KEY_USERNAME);
            logger.info("login username {}, callback url {}", userName, callbackUrl);
            if (callbackUrl != null && userName != null){
                return true;
            }
        }
        // 不存在callback信息,则跳转到配置页面
        response.sendRedirect(URL_CONFIG);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {

    }

}
